<?php require_once(dirname(__FILE__)."/../include/main.php"); ?>

<!-- Outline -->
<div id='picture'>
<div id='loading'><img src='img/loading.gif' /></div>
<a href='javascript:void();' rel='lightbox' target='_blank' id='pic-link'>
<img id='pic' alt='Picture not available?' text='What do you see?' />
</a>
</div>

<div id='selection'>
<table class='two-column'>
<tr>
<td>
<strong>Drag from here ...</strong>
<ul id='tags' class='tags'></ul>
</td>
<td>
<strong>... to here!</strong>
<ul id='selected-tags' class='tags'></ul>
</td>
</tr>
</table>

<div class='submit'>
<button id='submit' class='uibutton'>Submit</button>
</div>
</div>

<!-- Magic! -->
<script type='text/javascript'>
var CURRENT_PICTURE = null;

function loadTags() {
    if (CURRENT_PICTURE !== null) {
        $.get("ajax/loadTags.php?picId=" + CURRENT_PICTURE, function(data) {
            var c = data.length;
            for (var i = 0; i < c; i++) {
                t = data[i];
                if (t === null) continue;
                $("ul#tags").append('<li id="' + t.id + '">' + t.name + '<\/li>');
            }
        });
    }
}

function nextPicture() {
    CURRENT_PICTURE = null;
    $("ul.tags").empty();
    $("a#pic-link").attr("href", "javascript:void();");
    $("div#loading").show();
    $("img#pic").hide();

    $.get('ajax/nextPicture.php', function(data) {
        $("a#pic-link").attr("href", data.url);
        $("img#pic").attr("src", data.url);
        $("div#loading").hide();
        $("img#pic").show();
        CURRENT_PICTURE = data.id;
        loadTags();
    });
}

function validate(e) {
    if (CURRENT_PICTURE !== null) {
        tags = [];
        $("ul#selected-tags li").each(function (index,li) {
            tags.push(parseInt(li.id));
        });

        var params = { "picId": CURRENT_PICTURE, "tags": tags };
        $.post("ajax/submit.php", params, function(data) {
            if (data == null || data["error"] !== null) {
                alert("An Error occured" + (data !== null ? ": " + data["error"] : "."));
            } else {
                nextPicture();
            }
        })
        .fail(function () { alert("Something went wrong. Try again!"); });
    }
}

$(function() {
    $("button#submit").click(validate);
    $("ul.tags").sortable({ connectWith: "ul" });
    nextPicture();
});
</script>
